package com.apexedu.sync.controller;

import com.apexedu.encrypt.Encrypt;
import com.apexedu.identity.IdConstants;
import com.apexedu.identity.entity.TSysUser;
import com.apexedu.sync.contant.ActionConstant;
import com.apexedu.sync.contant.Constants;
import com.apexedu.sync.exception.AuCSyncException;
import com.apexedu.sync.service.ISyncService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 同步接入系统 用户、角色、资源及用户角色关系、角色资源关系
 * Created by ly on 2015/1/13.
 */
@Controller
public class SyncController {

    @Resource(name = "syncService")
    ISyncService syncService;

    /**
     * 同步接入系统
     *
     * @param request --
     * @return 同步结果
     */
    @RequestMapping(value = ActionConstant.RequestMapping_syncAllSystem, method = RequestMethod.POST)
    @ResponseBody
    public String syncSystem(HttpServletRequest request) {
        try {
            TSysUser user = (TSysUser) request.getSession().getAttribute(IdConstants.SESSION_USER);
            String msg = syncService.syncSystem(user, request.getParameter("appids"));
//            syncService.syncUser();
            return msg;
        } catch (AuCSyncException e) {
            //TODO
            return e.toString();
        }
    }

    /**
     * 业务系统直接调用的同步接口,不校验是否登录
     *
     * @param encrypt 校验码
     * @param request --
     * @return 同步结果
     */
    @RequestMapping(value = ActionConstant.RequestMapping_syncAllSystemNoLogin)
    @ResponseBody
    public String syncSystemNoLogin(@PathVariable(ActionConstant.Variable_encrypt) String encrypt,
                                    HttpServletRequest request) {
        try {
            if (!Encrypt.isMatch(encrypt))
                throw new AuCSyncException(AuCSyncException.ENCRYPT_NO_MATCH, "校验码未校验通过或已过期");
            TSysUser user = new TSysUser("接口调用");
            String msg = syncService.syncSystem(user, request.getParameter("appids"));
//            syncService.syncUser();
            return msg;
        } catch (AuCSyncException e) {
            //TODO
            return e.toString();
        }
    }
}
